﻿#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/spdlog.h>
#include <spdlog/async.h>
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"    
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <cstddef>
#include "logger.h"

// 假设你有实现这个函数，获取exe运行目录，返回带路径分隔符的字符串

#ifdef _WIN32
#include <windows.h>
#include <string>

std::string GetExeDir() {
    char path[MAX_PATH];
    GetModuleFileNameA(NULL, path, MAX_PATH);
    std::string fullPath(path);
    auto pos = fullPath.find_last_of("\\/");
    if (pos != std::string::npos)
        return fullPath.substr(0, pos);
    return "";
}

#else
#include <unistd.h>
#include <limits.h>
#include <string>

std::string GetExeDir() {
    char path[PATH_MAX];
    ssize_t count = readlink("/proc/self/exe", path, PATH_MAX);
    if (count != -1) {
        std::string fullPath(path, count);
        auto pos = fullPath.find_last_of('/');
        if (pos != std::string::npos)
            return fullPath.substr(0, pos);
    }
    return "";
}
#endif

std::shared_ptr<spdlog::logger> CreateFileLoggerWithTimestamp()
{
    auto now = std::chrono::system_clock::now();
    std::time_t now_c = std::chrono::system_clock::to_time_t(now);
    std::tm tm_local;
#ifdef _WIN32
    localtime_s(&tm_local, &now_c);
#else
    localtime_r(&now_c, &tm_local);
#endif
    std::ostringstream oss;
    oss << "/log-" << std::put_time(&tm_local, "%Y%m%d%H%M") << ".log";
    std::string exeDir = GetExeDir();
    std::string logFile = exeDir + "/" + oss.str();

#ifndef NDEBUG
    // Debug 模式：同时输出到文件和控制台
    auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
    auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(logFile, true);

    std::vector<spdlog::sink_ptr> sinks { console_sink, file_sink };
    auto logger = std::make_shared<spdlog::logger>("file_logger", sinks.begin(), sinks.end());
    std::cout << "Test 20250812 Debug Log file created at: " << logFile << std::endl;
#else
    // Release 模式：只输出到文件
    auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(logFile, true);
    auto logger = std::make_shared<spdlog::logger>("file_logger", file_sink);
    std::cout << "Test 20250812 Release Log file created at: " << logFile << std::endl;
#endif

    logger->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%l] [%t] [%s:%#] %v");
    spdlog::register_logger(logger);
    return logger;
}

